<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 云名片公共文件
 * 主要定义云名片公共函数库
 */

/* 解析列表定义规则*/
/**
 * 读取没有处理过的POST数据。相较于$HTTP_RAW_POST_DATA而言，它给内存带来的压力较小，
 * 并且不需要特殊的php.ini设置。php://input不能用于enctype=multipart/form-data。
 * 另外这里专门用来处理json数据
 * @return array
 */
function inputJson()
{
    return json_decode(file_get_contents('php://input'), true);
}
/**
 * 成功输出json
 * @param array $data 返回数据
 * @param array $expand 拓展的返回数据 例如总条数total等
 */
function successOutputJson($data = null,$expand = null)
{
    if($expand == null)
      exit(json_encode(['status' => 1,'data' => $data], JSON_UNESCAPED_UNICODE));
    else
      exit(json_encode(['status' => 1,'expand' => $expand, 'data' => $data], JSON_UNESCAPED_UNICODE));
}
/**
 * 异常输出json
 * @param string $info 异常提示信息
 * @param integer $type 信息类型
 * @param array $data 返回数据
 */
function abnormalOutputJson($expand = null,$data = null)
{
    if($expand == null)
      exit(json_encode(['status' => -1,'data' => $data], JSON_UNESCAPED_UNICODE));
    else
      exit(json_encode(['status' => -1,'expand' => $expand, 'data' => $data], JSON_UNESCAPED_UNICODE));
}

/**
 * 失败输出json
 * @param string $des 错误编码
 */
function errorOutputJson($des)
{
    exit(json_encode(['status' => 0, 'msg' => '错误码'.$des], JSON_UNESCAPED_UNICODE));
}

/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr){
  $vCity = array(
    '11','12','13','14','15','21','22',
    '23','31','32','33','34','35','36',
    '37','41','42','43','44','45','46',
    '50','51','52','53','54','61','62',
    '63','64','65','71','81','82','91'
  );
  if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
  if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
  $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
  $vLength = strlen($vStr);
  if ($vLength == 18) {
    $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
  } else {
    $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
  }
  if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
  if ($vLength == 18) {
    $vSum = 0;
    for ($i = 17 ; $i >= 0 ; $i--) {
      $vSubStr = substr($vStr, 17 - $i, 1);
      $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
    }
    if($vSum % 11 != 1) return false;
  }
  return true;
}

function getIp(){
  if (@$_SERVER['HTTP_CLIENT_IP'] && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } elseif (@$_SERVER['HTTP_X_FORWARDED_FOR'] && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  }
  return $ip;
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($data, $id = 1,$submit=0){
    $verify = new \Think\Verify();
    return $verify->sxcheck($data, $id,$submit);
}

function http_curl($url,$request_type='get',$data_type='json',$arr='')  
{  
    $ch=curl_init();//初始化curl  
    curl_setopt($ch, CURLOPT_URL, $url);//定义一些curl参数  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    if ($request_type=='post') {//如果是post请求  
        curl_setopt($ch, CURLOPT_POST, 1);  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);  
    }  
    $output=curl_exec($ch);//执行请求  
    if ($data_type=='json') {  
        if ( curl_errno($ch) ) {//如果请求出错，返回错误信息  
            return curl_error($ch);  
        }  
        else{//请求成功获取数据  
            $res=json_decode($output,true);  
        }  
        curl_close($ch);//curl关闭  
        return $res;//返回数据  
    }  
}

/**
 * 身份认证请求发送方法
 * @param string $uri
 * @param array $data
 * @return 参数格式不对返回false，成功返回请求结果
 */
function point_json_post_http_curl($data)
{
    if (!is_array($data))
        return false;
    //bblaiye.eicp.net

    $result = http_curl('http://www.ttc.com/iden.php/identify/doGet',
            'post', 'json', ['paramJson' => json_encode($data)]);
    return $result;
}


/**
 * 根据经纬度计算距离
 * @param string $lat1 纬度1
 * @param string $lng1 经度1
 * @param string $lat2 纬度2
 * @param string $lng2 经度2
 * @param string $miles true为m否则km
 * @return 参数格式不对返回false，成功返回请求结果
 */
function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
 $pi80 = M_PI / 180;
 $lat1 *= $pi80;
 $lng1 *= $pi80;
 $lat2 *= $pi80;
 $lng2 *= $pi80;
 $r = 6372.797; // mean radius of Earth in km
 $dlat = $lat2 - $lat1;
 $dlng = $lng2 - $lng1;
 $a = sin($dlat/2)*sin($dlat/2)+cos($lat1)*cos($lat2)*sin($dlng/2)*sin($dlng/2);
 $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
 $km = $r * $c;
 return ($miles ? ($km * 0.621371192) : $km);
}


function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {  
    $theta = $longitude1 - $longitude2;  
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));  
    $miles = acos($miles);  
    $miles = rad2deg($miles);  
    $miles = $miles * 60 * 1.1515;  
    $feet = $miles * 5280;  
    $yards = $feet / 3;  
    $kilometers = $miles * 1.609344;  
    $meters = $kilometers * 1000;  
    return compact('miles','feet','yards','kilometers','meters');  
}

/**
 * 获取文档封面图片
 * @param int $cover_id
 * @param string $field
 * @return 完整的数据  或者  指定的$field字段值
 * @author huajie <banhuajie@163.com>
 */
function get_cover($cover_id, $field = null){
    if(empty($cover_id)){
        return false;
    }
    $picture = M('Picture')->where(array('status'=>1))->getById($cover_id);
    if($field == 'path'){
        if(!empty($picture['url'])){
            $picture['path'] = $picture['url'];
        }else{
            $picture['path'] = __ROOT__.$picture['path'];
        }
    }
    return empty($field) ? $picture : $picture[$field];
}
/*
utf-8编码下截取中文字符串,参数可以参照substr函数
@param $str 要进行截取的字符串
@param $start 要进行截取的开始位置，负数为反向截取
@param $end 要进行截取的长度
func_num_args 返回传递到函数的参数数目 
*/
function utf8_substr($str,$start=0,$end) {
    if(empty($str)){
        return false;
    }
    if (function_exists('mb_substr')){
        if(func_num_args() >= 3) {
            $end = func_get_arg(2);
            return mb_substr($str,$start,$end,'utf-8');
        }
        else {
            mb_internal_encoding("UTF-8");
            return mb_substr($str,$start);
        }      
 
    }
    else {
        $null = "";
        preg_match_all("/./u", $str, $ar);
        if(func_num_args() >= 3) {
            $end = func_get_arg(2);
            return join($null, array_slice($ar[0],$start,$end));
        }
        else {
            return join($null, array_slice($ar[0],$start));
        }
    }
}
/**
* 可以统计中文字符串长度的函数
* @param $str 要计算长度的字符串
* @param $type 计算长度类型，0(默认)表示一个中文算一个字符，1表示一个中文算两个字符
*
*/
function abslength($str)
{
    if(empty($str)){
        return 0;
    }
    if(function_exists('mb_strlen')){
        // return 123;
        // function_exists 检查函数是否已定义
        return mb_strlen($str,'utf-8');
    }
    else {
        // return 235;
        preg_match_all("/./u", $str, $ar);
        return count($ar[0]);
    }
}
/**
 * 字符串超出长度尾部追加省略号
 * $text 要截取的字符串
 * $length 截取的长度
 * 超过长度 用什么代替
 */
function subtext($text, $length,$dot='...'){
    // return abslength($text);
    if(abslength($text) > $length){
        return utf8_substr($text, 0, $length).$dot;
    }
    return $text;
}

/**
 * 错误输出json
 * @param type $msg
 */
function errorOutputJson2($msg)
{
    exit(json_encode([
        'status' => 0,
        'sub_status' => '',
        'msg' => $msg,
        'data' => []
            ], JSON_UNESCAPED_UNICODE));
}

/**
 * 成功输出json
 * @param type $data
 */
function successOutputJson2($data = [])
{
    exit(json_encode([
        'status' => 1,
        'sub_status' => '',
        'msg' => '',
        'data' => $data
            ], JSON_UNESCAPED_UNICODE));
}
/**
 * 替换掉emoji表情
 * @param $text
 * @param string $replaceTo
 * @return mixed|string
 */
function filterEmoji($text, $replaceTo = '?')
{
    $clean_text = "";
    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clean_text = preg_replace($regexEmoticons, $replaceTo, $text);
    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clean_text = preg_replace($regexSymbols, $replaceTo, $clean_text);
    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clean_text = preg_replace($regexTransport, $replaceTo, $clean_text);
    // Match Miscellaneous Symbols
    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
    $clean_text = preg_replace($regexMisc, $replaceTo, $clean_text);
    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $clean_text = preg_replace($regexDingbats, $replaceTo, $clean_text);
    return $clean_text;
}
function replaceSpecialChar($strParam){
    $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
    return preg_replace($regex,"",$strParam);
}
/**
 * 商城请求
 * @param string $uri
 * @param array $data
 * @return 参数格式不对返回false，成功返回请求结果
 */
function mall_json_post_http_curl($uri, $data)
{
    if (!is_string($uri))
        return false;
    
    if (!is_array($data))
        return false;

    // $result = http_curl('https://www.6vbuy.com/member/index.php?'.$uri.'&com=6vbuy',
    //         'post', 'json', json_encode($data));
    $result = http_curl('http://www.b2b.com/member/index.php?'.$uri.'&com=6vbuy',
            'post', 'json', json_encode($data));
    return $result;
}

/**
 * 会员与长沙接口请求发送方法
 * @param string $uri
 * @param array $data
 * @return 参数格式不对返回false，成功返回请求结果
 * @ auther kong
 */
function member_json_post_http_curl($uri, $data)
{
    if (!is_string($uri))
        return false;
    if (!is_array($data))
        return false;
    $result = http_curl('http://www.6vbuy.com:9999/6v-center/'.$uri.'?access_token=12345',
            'post', 'json', $data);
    return $result;
}

